package com.kkb.service.impl;

import com.github.pagehelper.PageHelper;
import com.kkb.constant.QuestionConst;
import com.kkb.mapper.*;
import com.kkb.page.QueryPageBean;
import com.kkb.pojo.*;
import com.kkb.service.QuestionService;
import com.kkb.utils.StringUtils;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.util.*;

/**
 * 题库业务实现类
 */
@Service
public class QuestionServiceImpl implements QuestionService {
    @Autowired
    private TQuestionMapper questionMapper;
    @Autowired
    private TQuestionItemMapper questionItemMapper;
    @Autowired
    private TrQuestionTagMapper questionTagMapper;
    @Autowired
    private TCompanyMapper companyMapper;
    @Autowired
    private TrCompanyIndustryMapper companyIndustryMapper;
    @Autowired
    private TReviewLogMapper reviewLogMapper;
    @Autowired
    private TCatalogMapper catalogMapper;
    @Autowired
    private TTagMapper tTagMapper;
    @Autowired
    private TIndustryMapper industryMapper;

    @Override
    public List<TQuestion> findListByPage(QueryPageBean queryPageBean) {

        //获取查询参数
        Map queryParams = queryPageBean.getQueryParams();
        if(null == queryParams){
            queryParams = new HashMap();
        }
        queryParams.put("isClassic",0);//设置为不是精选题
        //设置分页信息
        PageHelper.startPage(queryPageBean.getPageNum(), queryPageBean.getPageSize());
        //调佣dao层查询
        List list = questionMapper.selectIsClassicByPage(queryParams);
        return list;
    }

    @Override
    @Transactional
    public int addOrUpdate(TQuestion question) {

        System.out.println("Service addOrUpdate:{}" + question);
        //保存题目信息
        int result = updateQuestion(question);
        // 保存题目选型信息
        int updateQuestiaaonItem = updateQuestiaaonItem(question);
        // 保存标签信息(题目与标签关系)
        int updateQuestionTag = updateQuestionTag(question);
        // 更新企业信息
        int updateCompany = updateCompany(question);

        return result;
    }

    //保存题目信息方法
    private int updateQuestion(TQuestion question){
        //题目初始化(isClassic=0,status=0,reviewStatus=0,createDate)
        question.setIsClassic(QuestionConst.ClassicStatus.CLASSIC_STATUS_NO.ordinal());
        question.setStatus(QuestionConst.Status.PRE_PUBLISH.ordinal());
        question.setReviewStatus(QuestionConst.ReviewStatus.PRE_REVIEW.ordinal ());
        question.setCreateDate(new Date());
        if(question.getId() == 0){
            int id = questionMapper.insert(question);
            System.out.println("新增成功id==="+question.getId());
            return id;
        }else{
            return questionMapper.updateByPrimaryKeySelective(question);
        }
    }

    //保存题目选型信息方法
    private int updateQuestiaaonItem (TQuestion question){
        int i = 0;
        //遍历选型列表，逐一保存
        for (TQuestionItem questionItem : question.getQuestionItemList()) {
            //其中某一题目选项
            // 设置选项的questionId
            questionItem.setQuestionId(question.getId());
            // 如果选项内容或选项为空，不插入到数据库
            if (StringUtils.isNull(questionItem.getContent()) || StringUtils.isEmpty(questionItem.getContent())) {
                if (StringUtils.isNull(questionItem.getImgUrl()) || StringUtils.isEmpty(questionItem.getImgUrl())) {
                    continue;
                }
            }
            //判断是添加还是更新
            if (questionItem.getId() == 0) {
                //新增
                questionItemMapper.insert(questionItem);
                i++;
            } else {
                //更新
                questionItemMapper.updateByPrimaryKeySelective(questionItem);
                i++;
            }
            //
//             if(true){ // 测试事务是否可行
//             i = 1/0; };
        }
        return i;
    }

    //更新题目标签关系方法
    private int updateQuestionTag(TQuestion question){
        int i =0;
        //先删除旧关系 ,根据questionId删除
        TrQuestionTagExample example = new TrQuestionTagExample();
        TrQuestionTagExample.Criteria criteria = example.createCriteria();
        criteria.andQuestionIdEqualTo(question.getId());
        questionTagMapper.deleteByExample(example);

        //新增新关系
        //遍历标签
        for(TTag tag:question.getTagList()){
        //构建关系
            TrQuestionTagKey questionTagKey = new TrQuestionTagKey();
            questionTagKey.setQuestionId(question.getId());
            questionTagKey.setTagId(tag.getId());
            questionTagMapper.insert(questionTagKey);
            i++;
        }return i;
    }

    //更新公司信息，包含与行业信息
    private int updateCompany(TQuestion question){
        int i =0;
        //更新公司信息
        TCompany company = question.getCompany();
        company.setUserId(question.getUserId());
        companyMapper.updateByPrimaryKeySelective(company);
        //更新公司与行业关系
        // 删除旧关系,根据companyId删除
        TrCompanyIndustryExample example = new TrCompanyIndustryExample();
        TrCompanyIndustryExample.Criteria criteria = example.createCriteria();
        criteria.andCompanyIdEqualTo(company.getId());
        companyIndustryMapper.deleteByExample(example);
        //新增公司行业关系
        // 遍历公司行业列表
        for(TIndustry industry:company.getIndustryList()){
            //构建关系
            TrCompanyIndustryKey companyIndustryKey = new TrCompanyIndustryKey();
            companyIndustryKey.setCompanyId(company.getId());
            companyIndustryKey.setIndustryId(industry.getId());
            companyIndustryMapper.insert(companyIndustryKey);
            i++;
        }return i;
    }

    //分页获取经典题目列表
    @Override
    public List<TQuestion> findClassicByPage(QueryPageBean queryPageBean) {
        Map map = queryPageBean.getQueryParams();
        if (null == map) {
            map = new HashMap();
        }
        //查询精选题目
        map.put("isClassic", 1);
        PageHelper.startPage(queryPageBean.getPageNum(), queryPageBean.getPageSize());
        List<TQuestion> questionList = questionMapper.selectIsClassicByPage(map);
        //获取每条记录的审核日志
        for(TQuestion question:questionList){
            TReviewLog reviewLog = reviewLogMapper.selectLastByQuestionId(question.getId());
        if(StringUtils.isNull(reviewLog)){
            reviewLog = new TReviewLog();
            reviewLog.setStatus(0);
            reviewLog.setComments("");
            reviewLog.setReviewer("");
            reviewLog.setCreateDate(null);
        }
        question.setReviewLog(reviewLog);
        }
        return questionList;
    }

    //根据id查询问题信息
    @Override
    public TQuestion findById(int questionId) {
        //1. 获取项目基本信息 级联获取题目选项信息
        System.out.println("查询ID"+questionId);
        TQuestion question = questionMapper.selectById(questionId);
        //2,查询学科目录信息
        initQuestionCataLog(question);
        //3.获取题目标签信息
        initQuestionTag(question);
        //4.根据公司id，获取所属公司信息
        initQuuestionCompany(question);
        return question;


    }

    //获取题目目录信息
    private void initQuestionCataLog(TQuestion question){
        TCatalog catalog = catalogMapper.selectByPrimaryKey(question.getCatalogId());
        question.setCatalog(catalog);
    }
    //获取题目标签信息
    private void initQuestionTag(TQuestion question){
        List<TTag> tagList = tTagMapper.selectTagListByQuestionId(question.getId());
        List<String> tagNameList = new ArrayList<>();
        for(TTag tag:tagList){
            tagNameList.add(tag.getName());
        }
        //设置标签名称列表
         question.setTagNameList(tagNameList);
        question.setTagList(tagList);
    }
    //获取题目所属公司及行业信息
    private void initQuuestionCompany(TQuestion question){
        TCompany company = companyMapper.selectByPrimaryKey(question.getCompanyId());
        //根据公司Id,获取所属行业信息
        List<TIndustry> industryList = industryMapper.selectIndustryListByCompany(question.getCompanyId());
        List<String> industryNameList = new ArrayList<>();
        for(TIndustry industry: industryList){
            industryNameList.add(industry.getName());
        }
        company.setIndustryNameList(industryNameList);
        company.setIndustryList(industryList);
        //设置所属公司（包含所属城市及行业）
        question.setCompany(company);
    }
}

